package org.dromara.creditcard.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.creditcard.domain.CreditMer;
import org.dromara.creditcard.domain.CreditOutRecord;
import org.dromara.creditcard.service.ICreditOutRecordService;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.dromara.common.mybatis.core.page.PageUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.system.domain.SysRole;
import org.dromara.system.service.ISysRoleService;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.web.core.BaseController;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.excel.utils.ExcelUtil;

/**
 * 刷卡账单记录
 *
 * @author Mr.Zhou
 * @date 2023-11-29
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/credit/outRecord")
public class CreditOutRecordController extends BaseController {

    private final ICreditOutRecordService creditOutRecordService;

    private final ISysRoleService sysRoleService;

    /**
     * 查询刷卡账单记录列表
     */
    @SaCheckPermission("credit:outRecord:list")
    @GetMapping("/list")
    public TableDataInfo<CreditOutRecord> list(CreditOutRecord creditOutRecord, PageQuery pageQuery) {
        Integer agentId = null;
        LoginUser loginUser = LoginHelper.getLoginUser();
        SysRole sysRole = sysRoleService.selectRoleByUserId(loginUser.getUserId());
        if(sysRole != null){
            if(sysRole.getRoleKey().equals("agent") || sysRole.getRoleKey().equals("business")) {
                agentId = loginUser.getAgentId();
            }
        }

        QueryWrapper<CreditOutRecord> qw = new QueryWrapper<>();
        if(agentId != null){
            qw.eq("agent_id", agentId);
        }else{
            if(creditOutRecord.getAgentId() != null){
                qw.eq("agent_id", creditOutRecord.getAgentId());
            }
        }

        if(creditOutRecord.getMonthRecordId() != null){
            qw.eq("month_record_id", creditOutRecord.getMonthRecordId());
        }

        Map<String, Object> params = creditOutRecord.getParams();
        if(params!=null){
            qw.between(params.get("beginTime") != null && params.get("endTime") != null,
                "bill_out_day", params.get("beginTime") + " 00:00:00", params.get("endTime") + " 23:59:59");
        }

        qw.orderByAsc("bill_out_day");

        TableDataInfo<CreditOutRecord> td = PageUtils.buildDataInfo(creditOutRecordService.page(PageUtils.buildPage(),qw));
        List<CreditOutRecord> list = td.getRows();
        return td;
    }

    /**
     * 导出刷卡账单记录列表
     */
    @SaCheckPermission("credit:outRecord:export")
    @Log(title = "刷卡账单记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(CreditOutRecord creditOutRecord, HttpServletResponse response) {
        QueryWrapper<CreditOutRecord> qw = new QueryWrapper<>();
        if(creditOutRecord.getParams()!= null){
            qw.between(creditOutRecord.getParams().get("beginTime") != null && creditOutRecord.getParams().get("endTime") != null,
                "bill_out_day", creditOutRecord.getParams().get("beginTime") + " 00:00:00", creditOutRecord.getParams().get("endTime") + " 23:59:59");
        }
        qw.orderByDesc("create_time");
        List<CreditOutRecord> list = creditOutRecordService.list(qw);
        if(CollUtil.isNotEmpty(list)){
            for (CreditOutRecord record : list){
                //记录类型 0 - 普通账号拆分记录 1 - 手动添加刷卡记录
                if(record.getRecordType() == 0){
                    record.setRecordTypeTxt("系统自动拆分");
                }else{
                    record.setRecordTypeTxt("手动添加刷卡记录");
                }
            }
        }
        ExcelUtil.exportExcel(list, "刷卡账单记录", CreditOutRecord.class, response);
    }

    /**
     * 获取刷卡账单记录详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("credit:outRecord:query")
    @GetMapping("/{id}")
    public R<CreditOutRecord> getInfo(@NotNull(message = "主键不能为空") @PathVariable Long id) {
        return R.ok(creditOutRecordService.getById(id));
    }

    /**
     * 新增刷卡账单记录
     */
    @SaCheckPermission("credit:outRecord:add")
    @Log(title = "刷卡账单记录", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody CreditOutRecord creditOutRecord) {

        creditOutRecord.setCreateTime(new Date());
        LoginUser loginUser = LoginHelper.getLoginUser();
        creditOutRecord.setAgentId(loginUser.getAgentId());

        return toAjax(creditOutRecordService.addOutRecord(creditOutRecord));
    }

    /**
     * 修改刷卡账单记录
     */
    @SaCheckPermission("credit:outRecord:edit")
    @Log(title = "刷卡账单记录", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody CreditOutRecord creditOutRecord) {
        return toAjax(creditOutRecordService.updateById(creditOutRecord));
    }

    /**
     * 删除刷卡账单记录
     *
     * @param ids 主键串
     */
    @SaCheckPermission("credit:outRecord:remove")
    @Log(title = "刷卡账单记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空") @PathVariable Long[] ids) {
        return toAjax(creditOutRecordService.removeByIds(Arrays.asList(ids)));
    }
}
